package com.multimedia.room.fragment;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.multimedia.room.AudioPlayActivity;
import com.multimedia.room.BaseActivity;
import com.multimedia.room.BaseActivity.IUpdateResources;
import com.multimedia.room.BaseFragment;
import com.multimedia.room.CommonUtil;
import com.multimedia.room.FilesEntity;
import com.multimedia.room.MediaMessage;
import com.multimedia.room.PlayActivity;
import com.multimedia.room.R;
import com.multimedia.room.fragment.SelfStudyFragment.IDestroyListener;

public class SelfAodFragment extends BaseFragment implements
        OnItemClickListener, IUpdateResources,
        IDestroyListener {

    // private ListView mDirListView;
    private ListView mPlayListView;
    private static final String TAG = SelfAodFragment.class.getSimpleName();


    // private String mPath = "/storage/external_storage/sda4/M2.mp4";
    private ArrayList<FilesEntity> mFileList = new ArrayList<FilesEntity>();
    private ArrayList<FilesEntity> mVideoList = new ArrayList<FilesEntity>();
    ;
    private ArrayList<FilesEntity> mAudioList = new ArrayList<FilesEntity>();
    ;
    private ArrayList<FilesEntity> mDocList = new ArrayList<FilesEntity>();
    ;
    private FileAdapter mFileAdapter;
    private static MediaMessage mMessage;
    private Context mContext;
    private int mCurrentIndex = 0;
    private String testUrl = "http://192.168.1.5:8080/list.xml";

    private static String mUrl;
    private String mPath = null;
    private Handler mHandler;

    private Spinner mSpinner;
    private HandlerThread mThread = new HandlerThread("study");
    private LinearLayout mEmptyView;
    private TextView mEmptyTitle;
    private ImageView mEmptyIcon;

    static int[] mContentEmptyIconIds =
            new int[]{R.drawable.icn_watermark_file_180x180, R.drawable.icn_watermark_video_180x180
                    , R.drawable.icn_watermark_audio_180x180, R.drawable.icn_watermark_file_180x180};

    static int[] mContentEmptyTitlesIds =
            new int[]{R.string.no_file_content, R.string.no_video_content, R.string.no_audio_content, R.string.no_doc_content};

    public static SelfAodFragment newInstance(MediaMessage message) {
        mMessage = message;
        Log.d(TAG, "message" + message.toString());
        SelfAodFragment fragment = new SelfAodFragment();
        return fragment;
    }

    public static SelfAodFragment newInstance() {
        SelfAodFragment fragment = new SelfAodFragment();
        return fragment;
    }

    private void init() {
        mThread.start();
        mHandler = new Handler(mThread.getLooper()) {

            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    final String result = (String) msg.obj;
                    SelfAodFragment.this.getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            if (!TextUtils.isEmpty(result)) {
                                try {
                                    Log.d("result ", result);
                                    mFileList = CommonUtil
                                            .getFilesEntityFromJson(result);
                                    Log.d(TAG, mFileList.toString());
                                    parseFileList();
                                    initAdapter(mCurrentIndex);
                                } catch (Exception e) {
                                    Log.w(TAG, "error" + e.toString());
                                }
                            }
                        }
                    });
                }
                super.handleMessage(msg);
            }

        };
    }

    @Override
    public void onAttach(Activity activity) {
        mContext = activity;
        super.onAttach(activity);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void initFilter() {
        String[] labels = mContext.getResources().getStringArray(R.array.filter_labels);
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext,
                android.R.layout.simple_spinner_item,
                labels);
        adapter.setDropDownViewResource(R.layout.drop_item);
        mSpinner.setAdapter(adapter);
        mSpinner.setSelection(0);
        addListenerToSpinner(mSpinner);
    }

    private void addListenerToSpinner(final Spinner spinner) {
        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "onItemSelected: pos: " + position + " id: " + id);
                TextView tv = (TextView) view;
                tv.setTextColor(getResources().getColor(R.color.mmclass_black));    //设置颜色
                tv.setGravity(android.view.Gravity.CENTER_HORIZONTAL);   //设置居中
                mSpinner.requestFocus();
                mCurrentIndex = position;
                initAdapter(mCurrentIndex);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.self_aod_layout, null);
        initView(rootView);
        return rootView;
    }

    private void initView(View rootView) {
        mSpinner = (Spinner) rootView.findViewById(R.id.filter1);
        mEmptyView = (LinearLayout) rootView.findViewById(R.id.empty);
        mEmptyIcon = (ImageView) rootView.findViewById(R.id.empty_icon);
        mEmptyTitle = (TextView) rootView.findViewById(R.id.empty_title);
        mPlayListView = (ListView) rootView.findViewById(R.id.file_list);
        mPlayListView.setOnItemClickListener(this);
        mPlayListView.setFocusableInTouchMode(true);
        mPlayListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.setActivated(true);
                return false;
            }
        });
        mVideoList = new ArrayList<FilesEntity>();
        mAudioList = new ArrayList<FilesEntity>();
        mDocList = new ArrayList<FilesEntity>();
        // mAudioList = MediaRoomDemo.sTestFiles;
        // mFileAdapter = new FileAdapter(mFileList);
        // mPlayListView.setAdapter(mFileAdapter);
        init();
        initFilter();
        implementsIupdate();
        SelfStudyFragment.registerDestroyListener(this);
        Log.d(TAG,
                "message"
                        + (mMessage == null ? "message is null" : mMessage
                        .toString()));
        if (mUrl == null) {
            return;
        }
        new MyTask().execute(mUrl);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    class MyTask extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... arg0) {
            String url = arg0[0];
            if (TextUtils.isEmpty(url)) {
                return "";
            }
            String result = CommonUtil.getFileData(url);
            return result;
        }

        protected void onPostExecute(String result) {
            if (result == null) {
                return;
            }
            if (!TextUtils.isEmpty(result)) {
                Log.d("result ", result);
                try {
                    mFileList = CommonUtil
                            .getFilesEntityFromJson(result);
                    Log.d(TAG, mFileList.toString());
                    parseFileList();
                    initAdapter(mCurrentIndex);
                } catch (Exception e) {
                    Log.e(TAG, "error" + e.toString());
                }
            }
        }

        ;
    }

    ;

    private void downloadResources(String url) {
        IDownLoadListener l = new IDownLoadListener() {

            @Override
            public void downloadComplete(String result) {
                if (result == null) {
                    return;
                }
                Message msg = mHandler.obtainMessage(1);
                msg.obj = result;
                mHandler.sendMessage(msg);
            }

        };
        DownLoadTask task = new DownLoadTask(url, l);
        mHandler.post(task);
    }

    ;

    class DownLoadTask implements Runnable {
        private String url;
        private IDownLoadListener l;

        public DownLoadTask(String url, IDownLoadListener listener) {
            this.url = url;
            this.l = listener;
        }

        @Override
        public void run() {
            String result = CommonUtil.getFileData(url);
            if (!TextUtils.isEmpty(result)) {
                l.downloadComplete(result);
            }
        }
    }

    interface IDownLoadListener {
        void downloadComplete(String result);
    }

    class FileAdapter extends BaseAdapter {

        private List<FilesEntity> mFiles = new ArrayList<FilesEntity>();
        private int mIndex = -1;

        public void setSelected(int index) {
            mIndex = index;
            notifyDataSetChanged();
        }

        public FileAdapter(List<FilesEntity> files) {
            mFiles = files;
        }

        @Override
        public int getCount() {
            return mFiles.size();
        }

        @Override
        public Object getItem(int position) {
            return mFiles.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            FilesEntity entity = mFiles.get(position);
            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(
                        R.layout.listem_item, null);
                holder = new ViewHolder();
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.mTitleView = (TextView) convertView.findViewById(R.id.item);
            holder.mIconView = (ImageView) convertView.findViewById(R.id.thumbnail);
            holder.mTitleView.setText(entity.getName());
            if (entity.isAudioFile()) {
                holder.mIconView.setImageResource(R.drawable.icn_thumbnail_audio_50x50);
            } else if (entity.isVideoFile()) {
                holder.mIconView.setImageResource(R.drawable.icn_thumbnail_video_50x50);
            } else if (entity.isDocFile()) {
                holder.mIconView.setImageResource(R.drawable.icn_thumbnail_file_50x50);
            }
//            if(mIndex == position){
//                convertView.setActivated(true);
//                convertView.setSelected(true);
////                convertView.requestFocus();
////                convertView.setBackgroundResource(R.drawable.focus_selector);
//            }else {
//                convertView.setActivated(false);
//            }
            return convertView;

        }


    }

    private static class ViewHolder {
        TextView mTitleView;
        ImageView mIconView;
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int arg2, long arg3) {

        if (mCurrentIndex == 0) {
            FilesEntity file = mFileList.get(arg2);
            if (isDocFile(file)) {
                DownLoadDialogFragment downloadDialogFragment = DownLoadDialogFragment
                        .newInstance(file);
                final FragmentManager fm = getFragmentManager();
                fm.beginTransaction();
                downloadDialogFragment.show(fm, "Download  fragment");
            } else if (isVideoFile(file)) {
                mPath = file.getUrl();
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                intent.setClass(mContext, PlayActivity.class);
                bundle.putParcelableArrayList("files", mVideoList);
                bundle.putString("name", file.getUrl());
                bundle.putString("title", file.getName());
                bundle.putInt("index", 0);
                intent.putExtras(bundle);
                startActivity(intent);
                this.getActivity().overridePendingTransition(R.anim.fade,
                        R.anim.hold);
            } else if (isAudioFile(file)) {
                mPath = file.getUrl();
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                intent.setClass(mContext, AudioPlayActivity.class);
                bundle.putParcelableArrayList("files", mAudioList);
                bundle.putString("name", file.getUrl());
                bundle.putString("title", file.getName());
                bundle.putInt("index", 0);
                intent.putExtras(bundle);
                startActivity(intent);
                this.getActivity().overridePendingTransition(R.anim.fade,
                        R.anim.hold);
            } else {
                Toast.makeText(mContext, "Can't support file", Toast.LENGTH_LONG).show();
            }

        } else if (mCurrentIndex == 1) {
            if (mVideoList != null && mVideoList.size() > 0) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                intent.setClass(mContext, PlayActivity.class);
                bundle.putParcelableArrayList("files", mVideoList);
                bundle.putString("name", mVideoList.get(arg2).getUrl());
                bundle.putString("title", mVideoList.get(arg2).getName());
                bundle.putInt("index", arg2);
                intent.putExtras(bundle);
                startActivity(intent);
                this.getActivity().overridePendingTransition(R.anim.fade,
                        R.anim.hold);
            }
        } else if (mCurrentIndex == 2) {
            if (mAudioList != null && mAudioList.size() > 0) {
                mPath = mAudioList.get(arg2).getUrl();
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                intent.setClass(mContext, AudioPlayActivity.class);
                bundle.putParcelableArrayList("files", mAudioList);
                bundle.putString("name", mAudioList.get(arg2).getUrl());
                bundle.putString("title", mAudioList.get(arg2).getName());
                bundle.putInt("index", arg2);
                intent.putExtras(bundle);
                startActivity(intent);
                this.getActivity().overridePendingTransition(R.anim.fade,
                        R.anim.hold);
            }

        } else if (mCurrentIndex == 3) {

            if (mDocList != null && mDocList.size() > 0) {
                FilesEntity file = mDocList.get(arg2);
                DownLoadDialogFragment downloadDialogFragment = DownLoadDialogFragment
                        .newInstance(file);
                final FragmentManager fm = getFragmentManager();
                fm.beginTransaction();
                downloadDialogFragment.show(fm, "Download  fragment");
            }
        }

    }

    @Override
    public void updateUrl(String url) {
        Log.d(TAG, "update resources " + url);
        mUrl = url;
        new MyTask().execute(url);
    }

    private void implementsIupdate() {
        if (this.getActivity() instanceof BaseActivity) {
            ((BaseActivity) this.getActivity()).setUpdateResources(this);
        }
    }

    private void initAdapter(int index) {
        if (mCurrentIndex == 0) {
            mFileAdapter = new FileAdapter(mFileList);
        } else if (mCurrentIndex == 1) {
            mFileAdapter = new FileAdapter(mVideoList);
        } else if (mCurrentIndex == 2) {
            mFileAdapter = new FileAdapter(mAudioList);
        } else if (mCurrentIndex == 3) {
            mFileAdapter = new FileAdapter(mDocList);
        }
        if (mFileAdapter != null && mFileAdapter.getCount() == 0) {
            mEmptyView.setVisibility(View.VISIBLE);
            mEmptyIcon.setImageResource(mContentEmptyIconIds[mCurrentIndex]);
            mEmptyTitle.setText(mContentEmptyTitlesIds[mCurrentIndex]);
            mPlayListView.setVisibility(View.GONE);
        } else {
            mEmptyView.setVisibility(View.GONE);
            mPlayListView.setVisibility(View.VISIBLE);
            mPlayListView.setAdapter(mFileAdapter);
            mPlayListView.setSelection(0);
        }
    }

    private void parseFileList() {
        mVideoList.clear();
        mAudioList.clear();
        mDocList.clear();
        for (FilesEntity fe : mFileList) {
            if (fe.getType().equalsIgnoreCase(".mp4")
                    || fe.getType().equalsIgnoreCase(".avi")
                    || fe.getType().equalsIgnoreCase(".rmvb")
                    || fe.getType().equalsIgnoreCase(".rm")
                    || fe.getType().equalsIgnoreCase(".wmv")
                    || fe.getType().equalsIgnoreCase(".3pg")
                    || fe.getType().equalsIgnoreCase(".flv")
                    || fe.getType().equalsIgnoreCase(".mkv")) {
                mVideoList.add(fe);
            } else if (fe.getType().equalsIgnoreCase(".mp3")
                    || fe.getType().equalsIgnoreCase(".wav")
                    || fe.getType().equalsIgnoreCase(".wma")) {
                mAudioList.add(fe);
            } else if (fe.getType().equalsIgnoreCase(".txt")
                    || fe.getType().equalsIgnoreCase(".doc")
                    || fe.getType().equalsIgnoreCase(".docx")
                    || fe.getType().equalsIgnoreCase(".xls")
                    || fe.getType().equalsIgnoreCase(".xlsx")
                    || fe.getType().equalsIgnoreCase(".pdf")
                    || fe.getType().equalsIgnoreCase(".ppt")
                    || fe.getType().equalsIgnoreCase(".pptx")
                    || fe.getType().equalsIgnoreCase(".png")
                    || fe.getType().equalsIgnoreCase(".jpg")
                    || fe.getType().equalsIgnoreCase(".jpeg")
                    || fe.getType().equalsIgnoreCase(".bmp")) {
                mDocList.add(fe);
            }
        }
    }


    private boolean isVideoFile(FilesEntity fe) {
        if (fe.getType().equalsIgnoreCase(".mp4")
                || fe.getType().equalsIgnoreCase(".avi")
                || fe.getType().equalsIgnoreCase(".rmvb")
                || fe.getType().equalsIgnoreCase(".rm")
                || fe.getType().equalsIgnoreCase(".wmv")
                || fe.getType().equalsIgnoreCase(".3pg")
                || fe.getType().equalsIgnoreCase(".flv")
                || fe.getType().equalsIgnoreCase(".mkv")) {
            return true;
        }
        return false;

    }

    private boolean isAudioFile(FilesEntity fe) {
        if (fe.getType().equalsIgnoreCase(".mp3")
                || fe.getType().equalsIgnoreCase(".wav")
                || fe.getType().equalsIgnoreCase(".wma")) {
            return true;
        }
        return false;

    }

    private boolean isDocFile(FilesEntity fe) {
        if (fe.getType().equalsIgnoreCase(".txt")
                || fe.getType().equalsIgnoreCase(".doc")
                || fe.getType().equalsIgnoreCase(".docx")
                || fe.getType().equalsIgnoreCase(".xls")
                || fe.getType().equalsIgnoreCase(".xlsx")
                || fe.getType().equalsIgnoreCase(".pdf")
                || fe.getType().equalsIgnoreCase(".ppt")
                || fe.getType().equalsIgnoreCase(".pptx")
                || fe.getType().equalsIgnoreCase(".png")
                || fe.getType().equalsIgnoreCase(".jpg")
                || fe.getType().equalsIgnoreCase(".jpeg")
                || fe.getType().equalsIgnoreCase(".bmp")) {
            return true;
        }
        return false;

    }


    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onDestroyView() {

        super.onDestroyView();
        SelfStudyFragment.unRegisterDestroyListener(this);
    }

    @Override
    public void destroy() {
        Log.d(TAG, "destroy()");
        mUrl = null;
        mVideoList = null;
        mDocList = null;
        mAudioList = null;
    }

}
